//
//  XGChatMenuView.m
//  HuanXin
//
//  Created by monkey on 2019/11/22.
//  Copyright © 2019 itcast. All rights reserved.
//

#import <Masonry/Masonry.h>
#import <UITextView_Placeholder/UITextView+Placeholder.h>

#import "XGChatMenuView.h"

/// 最大高度
static const CGFloat kInputViewMaxHeight = 150;
/// 最小高度
static const CGFloat kInputViewMinHeight = 36;

@interface XGChatMenuView () <UITextViewDelegate>

/// 输入视图
@property (nonatomic,strong) UITextView *inputTextView;
/// 上一次高度
@property (nonatomic,assign) CGFloat previousInputViewHeight;

@end

@implementation XGChatMenuView

#pragma mark - 构造方法

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [self setUpUI];
        _previousInputViewHeight = kInputViewMinHeight;
    }
    
    return self;
}

- (void)setUpUI
{
    [self addSubview:self.inputTextView];
    
    [_inputTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self);
        make.left.equalTo(self).offset(5);
        make.right.equalTo(self).offset(-5);
        make.height.mas_equalTo(kInputViewMinHeight);
        make.bottom.equalTo(self);
    }];
    
    UIView *separatorView = [[UIView alloc] init];
    separatorView.backgroundColor = [UIColor lightGrayColor];
    [self addSubview:separatorView];
    [separatorView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self);
        make.height.mas_equalTo(1.0 / [UIScreen mainScreen].scale);
    }];
}

#pragma mark - UITextViewDelegate

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]) {
        // 点击了发送
        if ([_delegate respondsToSelector:@selector(chatMenuView:sendMessage:)]) {
            textView.text = @"";
            [_delegate chatMenuView:self sendMessage:textView.text];
        }
        return NO;
    }
    
    return YES;
}

- (void)textViewDidChange:(UITextView *)textView
{
    CGFloat height = ceil([textView.text sizeWithFont:textView.font maxWidth:textView.bounds.size.width - 20].height);
    if (height < kInputViewMinHeight)
        height = kInputViewMinHeight;
    else if (height > kInputViewMaxHeight)
        height = kInputViewMaxHeight;
    if (height != _previousInputViewHeight) {
        [_inputTextView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(height);
        }];
        [self layoutIfNeeded];
        _previousInputViewHeight = height;
    }
}


#pragma mark - 懒加载

- (UITextView *)inputTextView
{
    if (!_inputTextView) {
        _inputTextView = [[UITextView alloc] init];
        _inputTextView.font = [UIFont systemFontOfSize:17];
        _inputTextView.placeholder = @"请输入内容";
        _inputTextView.returnKeyType = UIReturnKeySend;
        _inputTextView.delegate = self;
        _inputTextView.backgroundColor = [UIColor whiteColor];
    }
    
    return _inputTextView;
}

@end
